#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<queue>
using namespace std;
typedef  long long  int;   
const int N = 50;
const int inf = 0x3f3f3f3f;
char a[N][N];
int n, m;
int ret = 0;
map<pair<int, int>, int>key_lenth; //记录出口到达钥匙的最短路径  

void bfs(int i,int j) 
{
    int dx[] = { 0,0,1,-1 };
    int dy[] = { 1,-1,0,0 };
    bool vis[N][N] = { 0 };//标记数组
    queue<pair<int, int>>q;   
    q.push({ i,j }); 
    vis[i][j] = true; 
    int len = 0;

    while (q.size() )  
    {
        int sz = q.size();
        len++;
        while (sz--)   //拿到的钥匙数量不够
        {
            int srci = q.front().first;
            int srcj = q.front().second;   
            q.pop();
            for (int k = 0; k < 4; k++)
            {
                int x = srci + dx[k];
                int y = srcj + dy[k]; 
                if (x >= 0 && x < n && y >= 0 && y < m && vis[x][y]==false&&a[x][y] != '#'&&a[x][y]!='E')
                {
                   
                    if (a[x][y]=='K')
                    {
                        if (key_lenth[{x, y}]!=0)
                        {

                            ret = min(ret, key_lenth[{x, y}] + len);
                        }
                        else
                        {
                            key_lenth[{x, y}] = len;//拿到这个位置的钥匙,并标记最短路径
                   
                        }
                    }
                    q.push({ x,y });
                    vis[x][y] = true; 
                }
            }
        }
    }
}



void slove()
{
     cin >> n >> m;
    int peri = -1; int perj = 0;//人的起始坐标
    int doori = -1; int doorj = 0;//门的坐标

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> a[i][j];
            if (a[i][j] == 'P')
            {
                peri = i; perj = j;  
            }
            else if (a[i][j] == 'E')
            {
                doori = i; doorj = j;   
            }
        }
    }



    //先求人到钥匙的最短路径
    bfs(peri, perj);    
    bfs(doori, doorj);  //门到第一把钥匙最短路径


    if (ret==inf) 
        cout << "No solution" << endl;
    else 
    cout << ret << endl;   
}

signed main()
{
    int t = 0; cin >> t;
    while (t--)
    {
        key_lenth.clear();  
        ret = inf;
        slove();
    }
    return 0;
}


